package net.stuffrepos.bricknetcenter.util.validation;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class IntegerConstraint implements Constraint<Integer> {

    private static final Log log = LogFactory.getLog(IntegerConstraint.class);
    private final int minValue;
    private final int maxValue;
    private final boolean required;

    public IntegerConstraint(boolean required, Integer minValue, Integer maxValue) {
        this.required = required;
        this.minValue = (minValue == null ? Integer.MIN_VALUE : minValue);
        this.maxValue = (maxValue == null ? Integer.MAX_VALUE : maxValue);
    }

    @Override
    public boolean isValid(Integer value) {
        if (log.isTraceEnabled()) {
            log.trace("Testing integer value: " + value);
        }
        if (isRequired() && value == null) {
            if (log.isTraceEnabled()) {
                log.trace("Value is required");
            }
            return false;
        }

        if (value != null && value < getMinValue()) {
            if (log.isTraceEnabled()) {
                log.trace("Value is less than " + getMinValue());
            }
            return false;
        }

        if (value != null && value > getMaxValue()) {
            if (log.isTraceEnabled()) {
                log.trace("Value is greater than " + getMaxValue());
            }
            return false;
        }

        if (log.isTraceEnabled()) {
            log.trace("Value is valid");
        }

        return true;
    }

    public int getMinValue() {
        return minValue;
    }

    public int getMaxValue() {
        return maxValue;
    }

    public boolean isRequired() {
        return required;
    }
}
